package com.example.firstdemo.ui.screens.pages.login

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.firstdemo.network.service.AuthManager
import com.example.firstdemo.network.service.NetworkException
import com.example.firstdemo.network.service.UserManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch


class LoginViewModel() : ViewModel() {
    // UI 状态
    private val _uiState = MutableStateFlow(LoginUiState())
    val uiState = _uiState.asStateFlow()

    val isLoggedIn = UserManager.isLoggedIn

    fun login(username: String, password: String) {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, errorMessage = null)
            try {
                AuthManager.login(username, password)
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    loginSuccess = true,
                    errorMessage = null
                )
            } catch (e: NetworkException) {
//                _uiState.value = _uiState.value.copy(
//                    isLoading = false,
//                    loginSuccess = false,
//                    errorMessage = e.message
//                )
            }
        }
    }

    fun clearError() {
        _uiState.value = _uiState.value.copy(errorMessage = null)
    }
}